package com.sunducation.wts.penbox.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sunducation.wts.penbox.R;
import com.sunducation.wts.penbox.adapter.NoticeAdapter;
import com.sunducation.wts.penbox.contract.NoticeTaskContract;
import com.sunducation.wts.penbox.presenter.NoticeTaskPresenter;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.bean.request.CommitAssistantQuestionsOnlineReq;
import com.wetao.lib_common.bean.request.CommitAssistantQuestionsReq_vo;
import com.wetao.lib_common.bean.response.ReadPushListInfo;
import com.wetao.lib_common.bean.response.StudentExamListInfo;
import com.wetao.lib_common.bean.response.StudentLiveMessageInfo;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.greendao.model.AssistantExamOnline;
import com.wetao.lib_common.greendao.model.PagePictureOnline;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.GsonUtil;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.MultiClickUtil;
import com.wetao.lib_common.utils.QuestionTypeUtil;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.utils.oss.OssParams;
import com.wetao.lib_common.utils.oss.UploadOss;
import com.wetao.module_homework.HomeworkLineActivity;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * author: zhouyh
 * created on: 2021/6/8 10:59 上午
 * description:学习任务 和课堂互动公用界面
 */

@Route(path = ConstantArouter.PATH_APP_NOTICETASKACTIVITY)
public class NoticeTaskActivity extends BaseActivity<NoticeTaskContract.View, NoticeTaskPresenter> implements NoticeTaskContract.View {


    @Autowired
    String title;
    @Autowired
    int type;

    @BindView(R.id.notice_refresh_layout)
    SmartRefreshLayout srl;
    @BindView(R.id.lrv_task_list)
    RecyclerView lrv_task;
    @BindView(R.id.rl_noData)
    RelativeLayout rl_empty;
    @BindView(R.id.tv_noData)
    TextView tv_empty;


    private NoticeAdapter noticeAdapter;
    //直播数据
    private List<StudentLiveMessageInfo.Data> liveList = new LinkedList<>();
    //训练数据
    private List<StudentExamListInfo.Data.RecordsBean> examList = new LinkedList<>();
    //阅读推送数据
    private List<ReadPushListInfo.Data.RecordsBean> pushList = new LinkedList<>();


    int current = 1;
    int pages = 1;
    int total = 1;
    int PAGE_SIZE = 10;
    int PAGE = 1;
    String studentId;


    @Override
    public int getLayoutId() {
        return R.layout.activity_notice_task;
    }

    @Override
    public NoticeTaskPresenter createPresenter() {
        return new NoticeTaskPresenter(this);
    }

    @Override
    public NoticeTaskContract.View createView() {
        return this;
    }

    @Override
    public void init() {
        studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
        initTitleLayout();
        setTvTitle(title, true);
        initEvent();
        initRefresh();
        initRecycleView();
    }

    private void getDataRequest(int curPage) {
        //直播入口进去，不需要获取下面数据
        //主页更多进入，获取下面其他数据
        if (type == Constants.TYPE_TASK) {
            getPresenter().getHomeStudentExamList((HashMap<String, Object>) ComUtil.getHashmapByStr(
                    new String[]{"itemSubject", "state", "pageNo", "pageSize"}, new Object[]{null, 0, curPage, PAGE_SIZE}), false, false);
            getPresenter().getReadPushList(ComUtil.getHashmapByStr(
                    new String[]{"pageNo", "pageSize"},
                    new String[]{String.valueOf(curPage), String.valueOf(PAGE_SIZE)})
                    , false, false);
        }

        getPresenter().getStudentLiveMessageList((HashMap<String, Object>) ComUtil.getHashmapByStr(
                new String[]{"pageNo", "pageSize"}, new Object[]{curPage, PAGE_SIZE}), false, false);
    }


    /**
     * 获取更多请求
     * @param curPage
     */
    private void getMoreReq(int curPage) {

        if (type == Constants.TYPE_TASK) {
            getPresenter().getHomeStudentExamList((HashMap<String, Object>) ComUtil.getHashmapByStr(
                    new String[]{"itemSubject", "state", "pageNo", "pageSize"}, new Object[]{null, 0, curPage, PAGE_SIZE}), false, false);

            getPresenter().getReadPushList(ComUtil.getHashmapByStr(
                    new String[]{"pageNo", "pageSize"},
                    new String[]{String.valueOf(curPage), String.valueOf(PAGE_SIZE)})
                    , false, false);
        }
    }


    private void initRefresh() {
        srl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                if (current < pages) {
                    getMoreReq(++current);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                getDataRequest(current = PAGE);
            }
        });

        srl.setRefreshHeader(new ClassicsHeader(this));
        srl.setRefreshFooter(new ClassicsFooter(this));
    }


    private void initEvent() {
        iv_back.setOnClickListener(v -> finish());
        rl_empty.setOnClickListener(v -> getDataRequest(current));
    }

    private void initRecycleView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        lrv_task.setLayoutManager(linearLayoutManager);
        noticeAdapter = new NoticeAdapter(this);
        noticeAdapter.setNoticeItemClickListener(new NoticeAdapter.OnNoticeItemClickListener() {
            @Override
            public void OnClassItemClickListener(StudentLiveMessageInfo.Data bean, int position) {
                if (!ComUtil.isNetworkConnected()) {
                    ToastUtil.initToast("网络已断开，请先检查网络");
                    return;
                }
                if (MultiClickUtil.isFastClick()) {
                    ARouter.getInstance().build(ConstantArouter.PATH_CLASSIN_MAINROOMACTIVITY)
                            .withString("lessonName", bean.getLessonName())
                            .withString("roomName", bean.getRoomName())
                            .withString("studentId", String.valueOf(bean.getStudentId()))
                            .navigation();
                }
            }

            @Override
            public void OnExamItemClickListener(StudentExamListInfo.Data.RecordsBean item,int position) {
                if (item == null)return;
                if (3 == item.getState()) {//考试已结束,学生未提交
                    DialogXUtil.customDialogShow("当前作答已超时,\r\n已作答数据将自动提交。", "", "知道了", true, new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {

                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });
                    exceptionSubmitCount = 0;
                    setQuestionAnswer(item);
                    return;
                }

                if (0 == item.getState()) {//考试未开始
                    DialogXUtil.customDialogShow("当前未到作答时间,\n请在作答时间内作答。", "", "知道了", true, new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {

                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });
                    return;
                }

                ARouter.getInstance().build(ConstantArouter.PATH_HOMEWORK_LINEACTIVITY)
                        .withString("examName", item.getExamName())
                        .withInt("examId", item.getExamId())
                        .withInt("publishId", item.getExamPublishId())
                        .withInt("studentExamId", item.getStudentExamId())
                        .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        .navigation();
            }

            @Override
            public void OnPushItemClickListener(ReadPushListInfo.Data.RecordsBean bean) {
                gotoPushDetailActivity(bean);
            }

        });
        lrv_task.setAdapter(noticeAdapter);
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }


    @Override
    protected void onResume() {
        super.onResume();
        getDataRequest(current = PAGE);
    }

    @Override
    public void getStudentLiveMessageListResult(StudentLiveMessageInfo resp) {
        finishRefresh(Constants.TYPE_CLASS_INTERACTION);
        liveList.clear();
        if (resp.getData() != null && resp.getData().size() > 0) {
            liveList.addAll(resp.getData());
        }
        noticeAdapter.setClassData(liveList);
        showEmpty();

    }

    private void showEmpty() {
        if (noticeAdapter.getItemCount() > 0) {
            rl_empty.setVisibility(View.GONE);
            srl.setVisibility(View.VISIBLE);
        } else {
            rl_empty.setVisibility(View.VISIBLE);
            tv_empty.setText(type == Constants.TYPE_TASK ? "暂无学习任务" : "暂无课堂互动");
            srl.setVisibility(View.GONE);
        }
    }

    /**
     * 完成刷新
     *
     * @param type
     */
    private void finishRefresh(int type) {
        if (current == 1) {
            resetNoMoreData();
            if (type == Constants.TYPE_TASK) {
                examList.clear();
            } else if (type == Constants.TYPE_READ_PUSH) {
                pushList.clear();
            }
        }
        finishRefresh();
    }

    private void finishRefresh() {
        if (srl != null) {
            srl.finishRefresh();
            srl.finishLoadMore();
        }
    }

    public void resetNoMoreData() {
        if (srl != null) {
            srl.resetNoMoreData();//去除没有更多数据状态
        }
    }


    @Override
    public void getStudentLiveMessageListFail() {
        finishRefresh();
    }

    @Override
    public void getHomeStudentExamListResult(StudentExamListInfo resp) {
        finishRefresh(Constants.TYPE_TASK);
        if (resp.getData() != null && resp.getData().getSize() > 0) {
            for (int i = 0; i < resp.getData().getRecords().size(); i++) {
                StudentExamListInfo.Data.RecordsBean item = resp.getData().getRecords().get(i);
                AssistantExamOnline examOnline = DBUtils.getInstance(this).getAssistantExamOnlineByPublishId(item.getExamPublishId(), item.getExamId(), studentId);
                if (null != examOnline) {
                    item.setAnswerAmount(examOnline.getDealNum());
                }
            }
            examList.addAll(resp.getData().getRecords());
            pages = Math.max(pages, resp.getData().getPages()); //获取最大页数
            total = resp.getData().getTotal();
        }
        noticeAdapter.setExamData(examList);
        showEmpty();
    }

    @Override
    public void getHomeStudentExamListFail() {
        finishRefresh();
    }


    @Override
    public void getCommitAnswerResult(BaseResponse response) {
        ToastUtil.initToast("强制提交成功！");

        getDataRequest(current = PAGE);
    }

    @Override
    public void getCommitAnswerFailed() {
        ToastUtil.initToast("提交失败！");
    }

    @Override
    public void getReadPushListResult(ReadPushListInfo response) {
        finishRefresh(Constants.TYPE_READ_PUSH);
        ReadPushListInfo.Data data = response.getData();
        if (data != null) {
            //current = markingListResp.getCurrent();  //获得的结果一直是1，不准
            List<ReadPushListInfo.Data.RecordsBean> tempList = new ArrayList<>();
            tempList.addAll(data.getRecords());
            for (ReadPushListInfo.Data.RecordsBean bean : tempList) {
                if (bean.getReadStatus() == 3) {
                    pushList.add(bean);
                }
            }
            pages = Math.max(pages, data.getPages());
            noticeAdapter.setPushData(pushList);
        }
        showEmpty();
    }

    @Override
    public void getReadPushListFailed() {

    }


    private int exceptionSubmitCount = 0;

    private void setQuestionAnswer(StudentExamListInfo.Data.RecordsBean bean) {
        if (!ComUtil.isNetworkConnected()) {
            ToastUtil.initToast(getString(com.wetao.lib_common.R.string.network_disconnect));
            return;
        }

        List<CommitAssistantQuestionsReq_vo> answerList = new ArrayList<>();
        HashMap<String, String> answerMap = null;
        HashMap<Integer,Integer> timerMap = null;
        AssistantExamOnline assistantExam = DBUtils.getInstance(this).getAssistantExamOnlineByPublishId(bean.getExamPublishId(), bean.getExamId(), SPUtils.getInstance().getString(Constants.USER_ID_KEY));
        if (null != assistantExam && !TextUtils.isEmpty(assistantExam.getTempAnswer())
                && (answerMap = JsonUtils.fromJson(assistantExam.getTempAnswer(),
                new TypeToken<HashMap<String, String>>() {
                }.getType())) != null) {
            LogUtils.i("answerMap = " + GsonUtil.GsonString(answerMap));

            if (assistantExam.getTempTimer()!=null){
                timerMap = JsonUtils.fromJson(assistantExam.getTempTimer(),
                        new TypeToken<HashMap<Integer, Integer>>() {}.getType());
            }


            List<String> emptyNetList = null;
            for (Map.Entry<String, String> entry : answerMap.entrySet()) {
                String questionInfo = entry.getKey();
                String[] quest = questionInfo.split("###");
                if (QuestionTypeUtil.isSubjectQuestion(Integer.parseInt(quest[1]))
                        && !TextUtils.isEmpty(entry.getValue())) {
                    String[] tmp = entry.getValue().split("###");
                    for (int k = 0; k < tmp.length; k++) {
                        PagePictureOnline pagePicture = DBUtils.getInstance(this)
                                .getPagePictureOnlineByPictureLocal(tmp[k]);
                        if (null != pagePicture) {
                            if (TextUtils.isEmpty(pagePicture.getPictureUrl())
                                    && new File(pagePicture.getLocalPath()).exists()) {
                                if (null == emptyNetList) {
                                    emptyNetList = new ArrayList<>();
                                }
                                emptyNetList.add(pagePicture.getLocalPath());
                            }
                        }
                    }
                }
            }

            //当前有作答图盘不存在上传图片地址,递归上传图片,上传完后再提交
            if (null != emptyNetList && emptyNetList.size() > 0 && exceptionSubmitCount < 3) {
                exceptionSubmitCount++;
                // EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_UPLOAD_ERROR_SUBMIT, JsonUtils.toJson(emptyNetList)));
                uploadSubmit(emptyNetList, bean);
                return;
            }
            exceptionSubmitCount = 0;

            int key = 0;
            for (Map.Entry<String, String> entry : answerMap.entrySet()) {
                String item = entry.getValue();
                if (!TextUtils.isEmpty(item)) {
                    String question = entry.getKey();
                    if (TextUtils.isEmpty(question)) continue;

                    String[] quesInfo = question.split("###");
                    int questionId = Integer.parseInt(quesInfo[0]);
                    int questionType = Integer.parseInt(quesInfo[1]);

                    if (item.contains(".png") || item.contains(".jpg")) {
                        CommitAssistantQuestionsReq_vo answer = new CommitAssistantQuestionsReq_vo();
                        answer.setQuestionId(questionId);
                        answer.setQuestionType(questionType);
                        answer.setAnswerType(2);
                        answer.setCommitTime(timerMap!=null?timerMap.get(key):null);
                        LogUtils.d("item = " + item);
                        String picUrls = getPicUrls(item, emptyNetList);
                        LogUtils.d("picUrls = " + picUrls);
                        /*if (TextUtils.isEmpty(picUrls))
                            return;*/
                        answer.setAnswerContent(picUrls);
                        answerList.add(answer);
                    } else {
                        CommitAssistantQuestionsReq_vo answer = new CommitAssistantQuestionsReq_vo();
                        answer.setQuestionId(questionId);
                        answer.setQuestionType(questionType);
                        answer.setAnswerType(1);
                        answer.setCommitTime(timerMap!=null?timerMap.get(key):null);
                        answer.setAnswerContent(item);
                        answerList.add(answer);
                    }
                    key++;
                }
            }
        }

        CommitAssistantQuestionsOnlineReq req = new CommitAssistantQuestionsOnlineReq();
        req.setPublishId(bean.getExamPublishId());
        req.setStudentId(SPUtils.getInstance().getString(Constants.USER_ID_KEY));
        req.setStudentExamId(bean.getStudentExamId());

        req.setQuestionList(answerList);
        req.setFinishTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
        req.setBeginTime(null != assistantExam ? assistantExam.getBeginTime() : req.getFinishTime());

        getPresenter().getCommitAnswer(GsonUtil.GsonString(req), false, "正在提交已作答考试...", false);
    }

    private String getPicUrls(String str, List<String> exceptList) {
        String[] tmp = str.split("###");
        StringBuilder sb = new StringBuilder();

        for (int k = 0; k < tmp.length; k++) {
            if (null != exceptList && exceptList.contains(tmp[k])) continue;

            PagePictureOnline pagePicture = DBUtils.getInstance(this)
                    .getPagePictureOnlineByPictureLocal(tmp[k]);
            if (null != pagePicture && !TextUtils.isEmpty(pagePicture.getPictureUrl())) {
                sb.append(pagePicture.getPictureUrl());
                if (k != tmp.length - 1) {
                    sb.append(",");
                }
            }
        }

        return sb.toString();
    }

    private void uploadSubmit(List<String> exceptionPath, StudentExamListInfo.Data.RecordsBean bean) {
        //DialogXUtil.waitDialogShow("正在同步作答...");
        upload(exceptionPath, 0, new HomeworkLineActivity.OnListenProcess() {
            @Override
            public void onListenStart() {

            }

            @Override
            public void onListenEnd(String uploadFile, String localFile, List<String> list, int index, HomeworkLineActivity.OnListenProcess onListenProcess) {
                PagePictureOnline pagePictureOnline = DBUtils.getInstance(NoticeTaskActivity.this)
                        .getPagePictureOnlineByPictureLocal(localFile);
                if (null != pagePictureOnline) {
                    LogUtils.i(localFile + " : " + uploadFile);
                    pagePictureOnline.setPictureUrl(uploadFile);
                    DBUtils.getInstance(NoticeTaskActivity.this).updatePagePictureOnline(pagePictureOnline);
                }

                upload(list, index, onListenProcess);
            }

            @Override
            public void onListenError(List<String> list, int index, HomeworkLineActivity.OnListenProcess onListenProcess) {
                upload(list, index, onListenProcess);
            }

            @Override
            public void onListenAllEnd() {
                //DialogXUtil.waitDialogDismiss();
                setQuestionAnswer(bean);
            }
        });
    }

    private synchronized void upload(final List<String> list, final int index, final HomeworkLineActivity.OnListenProcess onListenProcess) {
        LogUtils.i("upload index = " + index + " size = " + list.size());
        if (index >= list.size()) {
            if (null != onListenProcess) {
                onListenProcess.onListenAllEnd();
            }
            return;
        }

        LogUtils.i("upload 002");
        final String temp = list.get(index);
        if (TextUtils.isEmpty(temp) || !new File(temp).exists()) {
            if (null != onListenProcess) {
                onListenProcess.onListenError(list, index + 1, onListenProcess);
            }
            return;
        }

        if (null != onListenProcess) {
            onListenProcess.onListenStart();
        }
        //这里保存的是原始图路径，需要转换成切图路径上传
        String clipPath = temp.substring(0,temp.lastIndexOf(".")) + "clip" + ".png";
        StringBuilder uploadFile = new StringBuilder();
        uploadFile.append(FileUtils.getFileNameNoExtension(clipPath));
        uploadFile.append("_");
        uploadFile.append(new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS").format(System.currentTimeMillis()));
        uploadFile.append(".png");
        LogUtils.i(temp + " : " + uploadFile.toString());
        UploadOss.getInstance().upload2OSS(uploadFile.toString(), clipPath, new UploadOss.OnUploadListener() {
            @Override
            public String uploadSuccess(String uploadFile, String localFile, OssParams ossParams) {
                if (null != onListenProcess) {
                    onListenProcess.onListenEnd(uploadFile, localFile, list, index + 1, onListenProcess);
                }
                return null;
            }

            @Override
            public String uploadFail(String uploadFile, String localFile, OssParams ossParams) {
                if (null != onListenProcess) {
                    onListenProcess.onListenError(list, index + 1, onListenProcess);
                }
                return null;
            }
        }, null);
    }


    /**
     * 跳转阅读页面
     *
     * @param bean
     */
    private void gotoPushDetailActivity(ReadPushListInfo.Data.RecordsBean bean) {
        if (bean == null || bean.getFileUrl() == null) {
            ToastUtil.initToast("没有找到文件路径");
            return;
        }
        ARouter.getInstance().build(ConstantArouter.PATH_READER_READPUSHDETAILACTIVITY)
                .withString("fileUrl", bean.getFileUrl())
                .withString("title", bean.getReadPushTitle())
                .withString("readPushItem", JsonUtils.toJson(bean))
                .withInt("state", bean.getReadStatus())
                .withString("records", JsonUtils.toJson(pushList))
                .navigation();
    }
}
